import { defineStore } from 'pinia';
import { childEnglishApi } from '@/api/childEnglishApi';

const DEFAULT_BASE_URL = 'http://localhost:8080';
const AUDIO_EXTENSIONS = ['mp3', 'wav', 'ogg', 'aac', 'm4a', 'flac'];
const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'avi'];
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
const PDF_EXTENSIONS = ['pdf'];
const TEXT_EXTENSIONS = ['txt', 'json', 'xml', 'csv', 'log', 'md'];
const OFFICE_EXTENSIONS = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];

export const usePreviewStore = defineStore('file-preview', {
  state: () => ({
    visible: false,
    fileName: '',
    displayName: '',
    fileType: '',
    fileExtension: '',
    baseUrl: DEFAULT_BASE_URL,
    previewUrl: '',
    downloadUrl: ''
  }),
  actions: {
    openPreview({ fileName, displayName, fileType }) {
      if (!fileName) {
        console.warn('openPreview 调用时缺少 fileName');
        return;
      }

      const extension = this.getExtension(fileName);
      const mappedType = fileType || this.mapExtensionToType(extension);
      const currentBase = childEnglishApi?.getCurrentServer?.() || DEFAULT_BASE_URL;
      const encodedName = encodeURIComponent(fileName);

      this.baseUrl = currentBase;
      this.fileName = fileName;
      this.displayName = displayName || fileName;
      this.fileExtension = extension;
      this.fileType = mappedType;
      this.previewUrl = `${currentBase}/file/preview/${encodedName}`;
      this.downloadUrl = `${currentBase}/file/download/${encodedName}`;
      this.visible = true;
    },
    closePreview() {
      this.visible = false;
      this.previewUrl = '';
      this.downloadUrl = '';
      this.fileName = '';
      this.displayName = '';
      this.fileExtension = '';
      this.fileType = '';
    },
    getExtension(fileName) {
      const lastDot = fileName.lastIndexOf('.');
      return lastDot > -1 ? fileName.substring(lastDot + 1).toLowerCase() : '';
    },
    mapExtensionToType(extension) {
      if (AUDIO_EXTENSIONS.includes(extension)) return 'audio';
      if (VIDEO_EXTENSIONS.includes(extension)) return 'video';
      if (IMAGE_EXTENSIONS.includes(extension)) return 'image';
      if (PDF_EXTENSIONS.includes(extension)) return 'pdf';
      if (TEXT_EXTENSIONS.includes(extension)) return 'text';
      if (OFFICE_EXTENSIONS.includes(extension)) return 'office';
      return 'other';
    }
  }
});

